package com.loong.common.mvc.exception;


import com.alibaba.fastjson.JSONObject;
import com.loong.common.enumerate.ResultCode;
import com.loong.common.exception.GlobalException;
import com.loong.common.rest.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingRequestHeaderException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(BindException.class)
    public Result bindExceptionHandler(BindException e) {
        String message = e.getFieldErrors().get(0).getDefaultMessage();
        return Result.fail().code(ResultCode.PARAM_ERROR.getCode()).message(message).build();
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result bindExceptionHandler(MethodArgumentNotValidException e) {
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        JSONObject error = new JSONObject();
        for (FieldError fieldError : fieldErrors) {
            error.put(fieldError.getField(),fieldError.getDefaultMessage());
        }
        return Result.fail().code(ResultCode.PARAM_ERROR.getCode()).data(error).message(ResultCode.PARAM_ERROR.getMessage()).build();
    }
    @ExceptionHandler(GlobalException.class)
    public Result globalExceptionHandler(GlobalException e) {
        log.error(e.getMessage(), e);
        return Result.fail().message(e.getExtraMessage()).code(e.getCode()).build();
    }

    @ExceptionHandler(MissingRequestHeaderException.class)
    public Result missingRequestHeaderExceptionHandler(MissingRequestHeaderException e) {
        log.error(e.getMessage(), e);
        return Result.fail().code(ResultCode.ILLEGAL_REQUEST.getCode()).message(e.getMessage()).build();
    }

    @ExceptionHandler(Exception.class)
    public Result exceptionHandler(Exception e) {
        log.error(e.getMessage(), e);
        return Result.fail().code(ResultCode.SERVER_ERROR.getCode()).message(e.getMessage()).build();
    }
}
